//
//  SLAreaCodeTableViewController.m
//  SLAppProduct
//
//  Created by Jianbo Cai on 2018/1/22.
//  Copyright © 2018年 Sunline. All rights reserved.
//

#import "JFAreaCodeTableViewController.h"
#import "JFAreaCodeEntity.h"
#import <JFBase/JFBase.h>

@interface JFAreaCodeTableViewController ()

// 地区数据形式【 {@"sectionTitle"：@"A" , @"areaArray" : @[]}，】
@property (nonatomic, strong) NSMutableArray *areaArray;            // 所有地区
@property (nonatomic, strong) NSMutableArray *titleArray;           // 标题

@property (nonatomic, assign) BOOL isEn;

@end

@implementation JFAreaCodeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = JFMainLocalizedString(@"bank.country");
    
    NSString *string = [JFInternationalHelper currentLanguage];
    if ([string isEqualToString:@"zh-Hans"]) {
        self.isEn = NO;
    }else if ([string isEqualToString:@"zh-Hant"]) {
        self.isEn = NO;
    }else {
        self.isEn = YES;
    }
    
}

// 按首字母分组排序数组
-(NSMutableArray *)sortObjectsAccordingToInitialWith:(NSArray *)arr {
    
    // 初始化UILocalizedIndexedCollation
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    //得出collation索引的数量，这里是27个（26个字母和1个#）
    NSInteger sectionTitlesCount = [[collation sectionTitles] count];
    //初始化一个数组newSectionsArray用来存放最终的数据，我们最终要得到的数据模型应该形如@[@[以A开头的数据数组], @[以B开头的数据数组], @[以C开头的数据数组], ... @[以#(其它)开头的数据数组]]
    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    for (int i = 0; i < sectionTitlesCount; i++) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:2];
        [dic setObject:[collation sectionTitles][i] forKey:@"sectionTitle"];
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];
        [dic setObject:array forKey:@"areaArray"];
        //初始化27个空字典加入newSectionsArray
        [newSectionsArray addObject:dic];
    }
    
    SEL selctor = self.isEn ? @selector(ENName) : @selector(CNName);
    
    //将每个名字分到某个section下
    for (JFAreaCodeEntity *personModel in arr) {
        //获取name属性的值所在的位置，比如"林丹"，首字母是L，在A~Z中排第11（第一位是0），sectionNumber就为11
        NSInteger sectionNumber = [collation sectionForObject:personModel collationStringSelector:selctor];
        //把name为“林丹”的p加入newSectionsArray中的第11个数组中去
        NSMutableArray *sectionNames = newSectionsArray[sectionNumber][@"areaArray"];
        [sectionNames addObject:personModel];
    }
    
    //对每个section中的数组按照name属性排序
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *personArrayForSection = newSectionsArray[index][@"areaArray"];
        NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:selctor];
//        newSectionsArray[index] = sortedPersonArrayForSection;
        [newSectionsArray[index] setObject:sortedPersonArrayForSection forKey:@"areaArray"];
    }
    
    //删除空的数组
    NSMutableArray *finalArr = [NSMutableArray new];
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableDictionary *dic = newSectionsArray[index];
        if (((NSMutableArray *)(dic[@"areaArray"])).count != 0) {
            [finalArr addObject:newSectionsArray[index]];
        }
    }
    
    return finalArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.areaArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic = self.areaArray[section];
    NSArray * areaArray = dic[@"areaArray"];
    return [areaArray count];
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID1 = @"cellIdentifier1";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID1];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID1];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
        label.textAlignment = NSTextAlignmentRight;
        cell.accessoryView = label;
    }
    
    NSArray *array = self.areaArray[indexPath.section][@"areaArray"];
    JFAreaCodeEntity *model = array[indexPath.row];
    UILabel *label = (UILabel *)cell.accessoryView;
    label.text = [NSString stringWithFormat:@"+%@", model.Code];
    cell.textLabel.text = self.isEn ? model.ENName : [JFStringHelper internationalString:model.CNName];
    [cell.textLabel setFont:JFPingFangFont(16)];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *string = self.titleArray[section];
    return string;
}


-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.titleArray;
}

//响应点击索引时的委托方法

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index {
    return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array = self.areaArray[indexPath.section][@"areaArray"];
    JFAreaCodeEntity *model = array[indexPath.row];
    //2.block传值
    if (self.returnCountryCodeBlock != nil) {
        self.returnCountryCodeBlock(model.Code);
    }
    [self.navigationController popViewControllerAnimated:true];
}

- (NSMutableArray *)areaArray {
    if (!_areaArray) {
        _areaArray = [self sortObjectsAccordingToInitialWith:[JFAreaCodeEntity getAllAreaCode]];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"sectionTitle", nil];
        [_areaArray insertObject:dic atIndex:0];
    }
    return _areaArray;
}


- (NSMutableArray *)titleArray {
    if (!_titleArray) {
        _titleArray = [NSMutableArray arrayWithCapacity:10];
        
        [self.areaArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [_titleArray addObject:(NSDictionary *)obj[@"sectionTitle"]];
        }];
    }
    return _titleArray;
}

@end
